Completed
Push — master ( 3ce364...b1ab6e )
by Andres
58s
created

angular.service(ꞌsavegameꞌ)   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
c 2
b 0
f 0
nc 1
dl 0
loc 3
rs 10
nop 0
1
/* globals versionCompare, atob, btoa */
2
/**
3
 savegame
4
 Service that handles save/load related functions.
5
6
 @namespace Services
7
 */
8
'use strict';
9
10
angular
11
  .module('game')
12
  .service('savegame', ['$state',
13
    'state',
14
    'data',
15
    function ($state, state, data) {
16
      this.initSave = function () {
17
        state.player = {};
18
        this.versionControl();
19
        state.init();
20
        $state.go('matter');
21
      };
22
23
      this.save = function () {
24
        localStorage.setItem('player', JSON.stringify(state.player));
25
      };
26
27
      this.load = function () {
28
        try {
29
          let storedPlayer = localStorage.getItem('player');
30
          if (!storedPlayer) {
31
            this.initSave();
32
          } else {
33
            state.player = JSON.parse(storedPlayer);
34
            this.versionControl();
35
          }
36
        } catch (err) {
37
          alert('Error loading savegame, reset forced.');
38
          this.initSave();
39
        }
40
      };
41
42
      this.versionControl = function () {
43
        // delete saves older than this version
44
        if (state.player.version && versionCompare(state.player.version, '2.1.0') < 0) {
45
          state.player = {};
46
        }
47
        // we merge the properties of the player with the start player to
48
        // avoid undefined errors with new properties
49
        state.player = angular.merge({}, data.start_player, state.player);
50
        // append an id if it doesn't exist
51
        if (!state.player.id) {
52
          state.player.id = Math.random().toString().substring(3);
53
        }
54
55
        // pre slots, reactions was an object
56
        if(!Array.isArray(state.player.reactions)){
57
          state.player.reactions = [];
58
        }
59
60
        // old saves may have outdated reactions, which crash the game
61
        for(let index in state.player.reactions){
62
          let reaction = state.player.reactions[index].reaction;
63
          for(let resource in reaction.reactant){
64
            if(typeof data.resources[resource] === 'undefined'){
65
              state.player.reactions.splice(index, 1);
66
            }
67
          }
68
        }
69
70
        // old saves may have outdated resources, which crash the game
71
        for(let resource in state.player.resources){
72
          if(typeof data.resources[resource] === 'undefined'){
73
            delete state.player.resources[resource];
74
          }
75
        }
76
      };
77
    }
78
  ]);
79